package com.stcc.portal.filter;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 描述:跨资源共享
 * 项目名:stcc_gl-parent
 * 包名:com.stcc.portal.filter
 * 作者:stcc
 * 创建时间:2021/3/11 10:22
 * 版本:1.0
 */
public class WebCorsFilter extends GenericFilterBean {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse res = (HttpServletResponse) response;
        HttpServletRequest req = (HttpServletRequest) request;

        String origin = req.getHeader("Origin");
        if (origin == null) {
            origin = req.getHeader("Referer");
        }

        res.setHeader("Access-Control-Allow-Origin", origin); // 允许指定域访问跨域资源
        res.setHeader("Access-Control-Allow-Credentials", "true"); // 允许客户端携带跨域cookie，此时origin值不能为“*”，只能为指定单一域名
        res.setHeader("Access-Control-Max-Age", "3600"); // 浏览器缓存预检请求结果时间,单位:秒
        res.setHeader("Access-Control-Expose-Headers", "Content-Type,Content-Disposition,Content-Length");

        String allowMethod = req.getHeader("Access-Control-Request-Method");
        if (null != allowMethod) {
            res.setHeader("Access-Control-Allow-Methods", allowMethod); // 允许浏览器在预检请求成功之后发送的实际请求方法名
        }

        String allowHeaders = req.getHeader("Access-Control-Request-Headers");
        if (null != allowHeaders) {
            res.setHeader("Access-Control-Allow-Headers", allowHeaders); // 允许浏览器发送的请求消息头
        }
        res.setHeader("Set-Cookie", "HttpOnly;Secure;SameSite=None");
        if (RequestMethod.OPTIONS.toString().equals(req.getMethod())) {
            return;
        }

        chain.doFilter(request, response);
    }

}
